<template>
  <ElDrawer v-model="opened" :title="formType" @close="closeHandler">
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" ref="formRef" label-width="100" :rules="rules" :disabled="isView">
      <ElFormItem label="上级区域" v-if="form.parentName">
        <ElTag size="large">{{ form.parentName }}</ElTag>
      </ElFormItem>
      <ElFormItem label="区域名称" prop="name">
        <ElInput placeholder="请输入名称" v-model="form.name" />
      </ElFormItem>
      <ElFormItem v-if="isAdd" label="区域编码" prop="id">
        <ElInput placeholder="请补全编码最后两位" v-model="form.id" maxlength="2">
          <template v-if="prefix" #prepend>{{ prefix }}</template>
        </ElInput>
      </ElFormItem>
      <ElFormItem v-else label="区域编码">
        <ElTag size="large">{{ form.id }}</ElTag>
      </ElFormItem>
      <ElFormItem label="排序">
        <ElInputNumber v-model="form.sortOrder" :min="0" :max="999" controls-position="right" />
      </ElFormItem>
      <ElFormItem label="区域层级">
        <ElTag>{{ form.level }} 级</ElTag>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton v-if="isView" @click="onCancelClicked">关闭</ElButton>
      <ElButton v-else @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, unref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { FormType } from '@/enums'
import { Area } from '@api/uc/area/interface'
import { getArea, addArea, updateArea, getDefault, checkExist } from '@api/uc/area'
import { validateDept } from '@/utils/validator'
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<Area.Form>>({})
const opened = ref(false)
const loading = ref(true)
const emit = defineEmits(['success'])

// open抽屉传参
interface FormParam {
  id?: string
  parentId?: string
}

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

const prefix = computed(() => {
  const value = form.value.parentId
  return value === '0' ? '' : value
})

// 权限校验
const validateCode = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const code = form.value.parentId === '0' ? value : form.value.parentId + value
  checkExist(code).then(resp => {
    if (resp.data) {
      callback(new Error('该编码已存在'))
    } else {
      callback()
    }
  })
}

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '区域名称不能为空', trigger: 'blur' },
    { max: 100, message: '区域名称最大长度 100', trigger: 'blur' }
  ],
  id: [
    { required: true, message: '区域编码不能为空', trigger: 'blur' },
    { max: 2, message: '区域编码最大长度 2', trigger: 'blur' },
    { validator: validateDept, trigger: 'blur' },
    { validator: validateCode, trigger: 'blur' }
  ],
  appcode: [{ max: 20, message: '应用编码最大长度 20', trigger: 'blur' }]
})

// 打开表单
async function open(type: FormType, param: FormParam) {
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    const { data } = await getDefault(param.parentId!)
    loading.value = false
    form.value = {
      parentId: param.parentId,
      parentName: data.parentName,
      level: data.parentLevel ? data.parentLevel + 1 : 1,
      sortOrder: data.currentSortOrder
    }
  } else {
    try {
      const { data } = await getArea(param.id!)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

// 关闭表单
function close() {
  loading.value = true
  opened.value = false
}

// 保存按钮
function onSaveClicked() {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const data = Object.assign({}, unref(form))
    if (isAdd.value) {
      addArea(data)
        .then(() => {
          success()
          sendSuccess()
          close()
        })
        .catch(error)
    } else {
      updateArea(data).then(() => {
        success()
        sendSuccess()
        close()
      })
    }
  })
}

// drawer关闭前事件处理
function closeHandler() {
  // menuTree.value = []
}

// 成功弹出提示
function success() {
  ElMessage({
    type: 'success',
    message: `成功!`
  })
}

// 成功失败弹出提示
function error(err: string) {
  ElMessage({
    type: 'error',
    message: `失败!  ${err}`
  })
}

// 取消按钮
function onCancelClicked() {
  close()
}

// 保存成功发送成功事件
function sendSuccess() {
  emit('success')
}

defineExpose({
  open,
  close
})
</script>
<style scoped lang="scss">
:deep(.el-input-group__prepend) {
  padding: 0 10px;
}
.el-tag--large {
  font-size: 14px;
}
</style>
